# -*- coding: utf-8 -*-
"""
智慧职教MOOC视频下载器 - 配置文件
包含所有的配置信息、headers、cookies等
"""

import os
import json
from pathlib import Path
from datetime import datetime


class Config:
    """配置管理类"""
    
    def __init__(self):
        # 基础配置
        self.CHROME_DEBUG_PORT = int(os.getenv('CHROME_DEBUG_PORT', 9527))
        self.CHROME_DEBUG_ADDRESS = f"127.0.0.1:{self.CHROME_DEBUG_PORT}"
        
        # 目录配置
        self.VIDEOS_DIR = os.getenv('VIDEOS_DIR', 'videos')
        self.LOGS_DIR = os.getenv('LOGS_DIR', 'logs')
        self.CONFIG_DIR = os.getenv('CONFIG_DIR', 'config')
        
        # 创建必要目录
        for directory in [self.VIDEOS_DIR, self.LOGS_DIR, self.CONFIG_DIR]:
            Path(directory).mkdir(exist_ok=True)
        
        # 下载配置
        self.MAX_DOWNLOAD_RETRIES = int(os.getenv('MAX_DOWNLOAD_RETRIES', 3))
        self.VIDEO_LOAD_TIMEOUT = int(os.getenv('VIDEO_LOAD_TIMEOUT', 10))
        self.PAGE_LOAD_TIMEOUT = int(os.getenv('PAGE_LOAD_TIMEOUT', 30))
        self.REQUEST_TIMEOUT = int(os.getenv('REQUEST_TIMEOUT', 30))
        
        # 课程处理配置
        self.MAX_CONSECUTIVE_FAILURES = int(os.getenv('MAX_CONSECUTIVE_FAILURES', 3))
        self.COMPLETION_RATE_THRESHOLD = float(os.getenv('COMPLETION_RATE_THRESHOLD', 0.9))
        self.MIN_FILE_SIZE = int(os.getenv('MIN_FILE_SIZE', 10240))  # 最小文件大小（字节）
        
        # 并发配置
        self.MAX_CONCURRENT_DOWNLOADS = int(os.getenv('MAX_CONCURRENT_DOWNLOADS', 1))
        self.ENABLE_PARALLEL_PROCESSING = os.getenv('ENABLE_PARALLEL_PROCESSING', 'false').lower() == 'true'
        
        # 网站URL
        self.BASE_URL = "https://mooc.icve.com.cn"
        self.MOOC_INDEX_URL = "https://mooc.icve.com.cn/learning/u/student/student/mooc_index.action"
        
        # 加载用户配置
        self._load_user_config()
    
    def _load_user_config(self):
        """从文件加载用户配置"""
        config_file = Path(self.CONFIG_DIR) / "user_config.json"
        
        if config_file.exists():
            try:
                with open(config_file, 'r', encoding='utf-8') as f:
                    user_config = json.load(f)
                    
                # 更新cookies和headers
                if 'cookies' in user_config:
                    self.COOKIES = user_config['cookies']
                else:
                    self._set_default_cookies()
                    
                if 'headers' in user_config:
                    self.HEADERS = user_config['headers']
                else:
                    self._set_default_headers()
                    
            except Exception as e:
                print(f"警告：加载用户配置失败，使用默认配置: {e}")
                self._set_default_cookies()
                self._set_default_headers()
        else:
            # 创建默认配置文件
            self._set_default_cookies()
            self._set_default_headers()
            self.save_user_config()
    
    def _set_default_cookies(self):
        """设置默认cookies"""
        self.COOKIES = {
            'alicfw': '457492428%7C1969853035%7C1328233698%7C1328232707',
            'alicfw_gfver': 'v1.200309.1',
            'aliyungf_tc': '9c4cd8cb9b13c0aac345333c43d95871fcdfa1a193ad66f47c215d723b0c6a9f',
            '_abfpc': '6fedd8f857641cd9187bb58d0cf39c485d4ce3f1_2.0',
            'Hm_lvt_7dce8ed3f950521c9d3bdf26898fe9a8': '1749461027',
            'HMACCOUNT': '88971C3D2A206AF1',
            'cna': 'c240271fa0946aba5c8bd3955c233a2a',
            'token': '62dc774b-4e06-48f2-81d8-8c2b1a94a289',
            '_uid': '0ef8f6c9-9acf-4b8b-bbc1-8eda7f40a88b',
            'acw_tc': 'ac11000117494723423101283ec6ccc8623a69fdef0ba5fd4a6cfc7b5a95a8',
            'Hm_lvt_8129a2192baa6850d14267505464231c': '1749472922',
            'Hm_lpvt_8129a2192baa6850d14267505464231c': '1749472922',
            'Hm_lpvt_7dce8ed3f950521c9d3bdf26898fe9a8': '1749473034',
            'JSESSIONID': '01250387B87555AFF24309016C2FD6ED.yunpan-tomcat-yunpan_sdk_aliyun',
            'SERVERID': 'dcb6dc01f97b91d9fbb10e16ceac63ec|1749473036|1749461025',
        }
    
    def _set_default_headers(self):
        """设置默认headers"""
        self.HEADERS = {
            'Accept': 'application/json, text/javascript, */*; q=0.01',
            'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6',
            'Connection': 'keep-alive',
            'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
            'Origin': 'https://mooc.icve.com.cn',
            'Referer': 'https://mooc.icve.com.cn/cms/courseDetails/index.htm',
            'Sec-Fetch-Dest': 'empty',
            'Sec-Fetch-Mode': 'cors',
            'Sec-Fetch-Site': 'same-origin',
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/137.0.0.0 Safari/537.36 Edg/137.0.0.0',
            'X-Requested-With': 'XMLHttpRequest',
            'sec-ch-ua': '"Microsoft Edge";v="137", "Chromium";v="137", "Not/A)Brand";v="24"',
            'sec-ch-ua-mobile': '?0',
            'sec-ch-ua-platform': '"Windows"',
        }
    
    def save_user_config(self):
        """保存用户配置到文件"""
        config_file = Path(self.CONFIG_DIR) / "user_config.json"
        
        config_data = {
            'cookies': self.COOKIES,
            'headers': self.HEADERS,
            'last_updated': datetime.now().isoformat(),
            'version': '2.0'
        }
        
        try:
            with open(config_file, 'w', encoding='utf-8') as f:
                json.dump(config_data, f, ensure_ascii=False, indent=2)
            print(f"✅ 配置已保存到: {config_file}")
        except Exception as e:
            print(f"❌ 保存配置失败: {e}")
    
    def update_cookies(self, new_cookies):
        """更新cookies"""
        self.COOKIES.update(new_cookies)
        self.save_user_config()
    
    def update_headers(self, new_headers):
        """更新headers"""
        self.HEADERS.update(new_headers)
        self.save_user_config()


# 全局配置实例
config = Config()

# 向后兼容的变量导出
CHROME_DEBUG_PORT = config.CHROME_DEBUG_PORT
CHROME_DEBUG_ADDRESS = config.CHROME_DEBUG_ADDRESS
VIDEOS_DIR = config.VIDEOS_DIR
MAX_DOWNLOAD_RETRIES = config.MAX_DOWNLOAD_RETRIES
VIDEO_LOAD_TIMEOUT = config.VIDEO_LOAD_TIMEOUT
PAGE_LOAD_TIMEOUT = config.PAGE_LOAD_TIMEOUT
MAX_CONSECUTIVE_FAILURES = config.MAX_CONSECUTIVE_FAILURES
COMPLETION_RATE_THRESHOLD = config.COMPLETION_RATE_THRESHOLD
BASE_URL = config.BASE_URL
MOOC_INDEX_URL = config.MOOC_INDEX_URL
COOKIES = config.COOKIES
HEADERS = config.HEADERS 